#include "utils/json_utils.h"
#include <filesystem>
#include <spdlog/spdlog.h>

namespace utils {

nlohmann::json JsonUtils::loadFromFile(const std::string& filepath) {
    // 检查文件是否存在
    if (!std::filesystem::exists(filepath)) {
        SPDLOG_ERROR("JSON file not found: {}", filepath);
        throw std::runtime_error("JSON file not found: " + filepath);
    }

    std::ifstream file(filepath);
    if (!file.is_open()) {
        SPDLOG_ERROR("Failed to open JSON file: {}", filepath);
        throw std::runtime_error("Failed to open JSON file: " + filepath);
    }

    nlohmann::json config;
    try {
        file >> config;
        SPDLOG_DEBUG("Successfully loaded JSON from: {}", filepath);
    } catch (const nlohmann::json::parse_error& e) {
        SPDLOG_ERROR("JSON parse error in {}: {}", filepath, e.what());
        throw std::runtime_error("JSON parse error in " + filepath + ": " + e.what());
    }

    return config;
}

void JsonUtils::saveToFile(const std::string& filepath, const nlohmann::json& j) {
    // 确保目录存在
    std::filesystem::path path(filepath);
    if (!path.parent_path().empty()) {
        std::filesystem::create_directories(path.parent_path());
    }

    std::ofstream file(filepath);
    if (!file.is_open()) {
        SPDLOG_ERROR("Failed to create JSON file: {}", filepath);
        throw std::runtime_error("Failed to create JSON file: " + filepath);
    }

    try {
        file << j.dump(4); // 使用4个空格缩进
        SPDLOG_DEBUG("Successfully saved JSON to: {}", filepath);
    } catch (const std::exception& e) {
        SPDLOG_ERROR("Failed to write JSON file {}: {}", filepath, e.what());
        throw std::runtime_error("Failed to write JSON file " + filepath + ": " + e.what());
    }
}

} // namespace utils